package com.atguigu.juc.day02.communication;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo01Normal {

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    private int number = 0;

    public void doAdd() {

        try {
            lock.lock();

            while (number > 0) {
                // 让当前线程进入等待
                condition.await();
            }

            // 核心业务
            System.out.println(Thread.currentThread().getName() + " 执行加法：" + ++number);

            // 唤醒全部其它线程
            condition.signalAll();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            lock.unlock();

        }
    }

    public void doSub() {

        try {
            lock.lock();

            while (number == 0) {
                // 让当前线程进入等待
                condition.await();
            }

            // 核心业务
            System.out.println(Thread.currentThread().getName() + " 执行减法：" + --number);

            // 唤醒全部其它线程
            condition.signalAll();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            lock.unlock();

        }
    }

    public static void main(String[] args) {

        Demo01Normal demo = new Demo01Normal();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                demo.doAdd();
            }
        }, "thread-add01").start();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                demo.doAdd();
            }
        }, "thread-add02").start();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                demo.doSub();
            }
        }, "thread-sub01").start();

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                demo.doSub();
            }
        }, "thread-sub02").start();

    }

}
